﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Microsoft.Practices.Unity;

namespace ERPStore.Indexers.Lucene.Services
{
	public class StoreAnalyzer : Analyzer
	{
		private global::Lucene.Net.Util.Version m_LuceneVersion;

		public StoreAnalyzer(Models.Settings settings)
		{
			UseFrenchStemFilter = settings.useFrenchStemFilter;
			var stopWorsConfig = settings.StopWords;
			if (stopWorsConfig != null)
			{
				StopWords = stopWorsConfig.Split(',');
			}
			m_LuceneVersion = global::Lucene.Net.Util.Version.LUCENE_29;
		}

		public StoreAnalyzer(ICompensatorRepository compensatorRepository
			, Models.Settings settings) 
			: this(settings)
		{
			this.CompensatorRepository = compensatorRepository;
		}

		public bool UseFrenchStemFilter { get; set; }
		public string[] StopWords { get; set; }
		[Dependency]
		public ICompensatorRepository CompensatorRepository { get; set; }

		public override TokenStream TokenStream(string fieldName, System.IO.TextReader reader)
		{
			TokenStream result = new StandardTokenizer(m_LuceneVersion, reader);

			result = new StandardFilter(result);
			// result = new ISOLatin1AccentFilter(result);
			if (StopWords != null)
			{
				result = new StopFilter(true, result, StopWords, true);
			}
			if (UseFrenchStemFilter)
			{
				result = new global::Lucene.Net.Analysis.Fr.FrenchStemFilter(result);
			}
			if (CompensatorRepository != null)
			{
				result = new CompensatorFilter(result, CompensatorRepository);
			}
			result = new LowerCaseFilter(result);
			result = new ASCIIFoldingFilter(result);

			return result;
		}
	}
}
